<template>
  <view class="withdrawal-record-page">
    <!-- 页面内容 -->
    <scroll-view 
      class="scroll-content" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 统计信息卡片 -->
      <view class="stats-card">
        <view class="stats-item">
          <text class="stats-value">{{ recordStats.totalCount || 0 }}</text>
          <text class="stats-label">总提现次数</text>
        </view>
        <view class="stats-divider"></view>
        <view class="stats-item">
          <text class="stats-value">¥{{ formatAmount(recordStats.totalAmount) }}</text>
          <text class="stats-label">累计提现金额</text>
        </view>
      </view>

      <!-- 提现记录列表 -->
      <view class="record-list">
        <view 
          class="record-item" 
          v-for="(item, index) in recordList" 
          :key="index"
          @click="showRecordDetail(item)"
        >
          <!-- 左侧状态图标 -->
          <view class="record-status">
            <view class="status-icon" :class="'status-' + item.status">
              <u-icon :name="getStatusIcon(item.status)" size="32" :color="getStatusColor(item.status)"></u-icon>
            </view>
          </view>

          <!-- 中间内容区域 -->
          <view class="record-content">
            <!-- 第一行：提现金额和状态 -->
            <view class="record-header">
              <text class="amount">¥{{ formatAmount(item.amount) }}</text>
              <view class="status-badge" :class="'status-' + item.status">
                <text class="status-text">{{ getStatusText(item.status) }}</text>
              </view>
            </view>

            <!-- 第二行：银行信息 -->
            <view class="bank-info">
              <text class="bank-name">{{ item.bankName || '-' }}</text>
              <text class="bank-card">{{ formatBankCard(item.bankCardNo) }}</text>
            </view>

            <!-- 第三行：审批时间 -->
            <view class="approval-time">
              <text class="time-label">
                {{ item.status === 0 ? '申请时间' : (item.status === 1 ? '打款时间' : '拒绝时间') }}：
              </text>
              <text class="time-value">
                {{ formatTime(item.status === 0 ? item.createTime : item.approvalTime) }}
              </text>
            </view>
          </view>

          <!-- 右侧箭头 -->
          <view class="record-arrow">
            <u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="recordList.length === 0 && !loading">
          <view class="empty-icon">📋</view>
          <text class="empty-title">暂无提现记录</text>
          <text class="empty-desc">您还没有发起过提现申请</text>
        </view>

        <!-- 加载状态 -->
        <view class="load-status" v-if="recordList.length > 0">
          <view class="load-more" v-if="hasMore">
            <text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
          </view>
          <view class="no-more" v-else>
            <text class="no-more-text">没有更多记录了</text>
          </view>
        </view>
      </view>

      <!-- 底部安全区域 -->
      <view class="safe-area-bottom"></view>
    </scroll-view>

    <!-- 记录详情弹出层 -->
    <u-popup
      :show="showDetailPopup"
      mode="bottom"
      height="60%"
      border-radius="20"
      closeable
      @close="closeDetailPopup"
    >
      <view class="detail-popup" v-if="selectedRecord">
        <view class="detail-header">
          <text class="detail-title">提现详情</text>
        </view>

        <view class="detail-content">
          <view class="detail-item">
            <text class="detail-label">提现金额</text>
            <text class="detail-value amount-value">¥{{ formatAmount(selectedRecord.amount) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">状态</text>
            <view class="status-badge" :class="'status-' + selectedRecord.status">
              <text class="status-text">{{ getStatusText(selectedRecord.status) }}</text>
            </view>
          </view>
          <view class="detail-item">
            <text class="detail-label">提现银行</text>
            <text class="detail-value">{{ selectedRecord.bankName || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">银行卡号</text>
            <text class="detail-value">{{ selectedRecord.bankCardNo || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">持卡人</text>
            <text class="detail-value">{{ selectedRecord.cardHolder || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">申请时间</text>
            <text class="detail-value">{{ formatTime(selectedRecord.createTime) }}</text>
          </view>
          <view class="detail-item" v-if="selectedRecord.approvalTime && selectedRecord.status !== 0">
            <text class="detail-label">{{ selectedRecord.status === 1 ? '打款时间' : '拒绝时间' }}</text>
            <text class="detail-value">{{ formatTime(selectedRecord.approvalTime) }}</text>
          </view>
          <view class="detail-item" v-if="selectedRecord.note">
            <text class="detail-label">备注</text>
            <text class="detail-value">{{ selectedRecord.note }}</text>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopId: '',
      cardId: '',
      recordList: [],
      pageNo: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      refreshing: false,
      recordStats: {
        totalCount: 0,
        totalAmount: 0
      },
      // 详情弹出层
      showDetailPopup: false,
      selectedRecord: null
    }
  },
  onLoad(option) {
    console.log('option', option);
    this.shopId = option.shopId || ''
    this.cardId = option.cardId || ''
    this.loadRecordList()
  },
  methods: {
    // 加载提现记录列表
    async loadRecordList(isLoadMore = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const params = {
        userId: this.cardId,
          pageNo: isLoadMore ? this.pageNo : 1,
          pageSize: this.pageSize,
        column: "createTime",
        order: 'desc'
      }

        if (!isLoadMore) {
          this.pageNo = 1
          this.hasMore = true
          this.recordList = []
        }

        const res = await this.$api.getShopWithdrawalList(params)
        
        if (res.success && res.result) {
          const newList = res.result.records || []
          this.recordList = isLoadMore ? [...this.recordList, ...newList] : newList
          
          const total = res.result.total || 0
          this.hasMore = this.recordList.length < total
          
          // 计算统计信息
          this.calculateStats()
          
          console.log('提现记录', res.result)
        }
      } catch (error) {
        console.error('获取提现记录失败:', error)
        uni.showToast({
          title: '获取记录失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return
      this.pageNo += 1
      this.loadRecordList(true)
    },

    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadRecordList()
    },

    // 计算统计信息
    calculateStats() {
      const totalCount = this.recordList.length
      const totalAmount = this.recordList.reduce((sum, item) => {
        return sum + (parseFloat(item.amount) || 0)
      }, 0)
      
      this.recordStats = {
        totalCount,
        totalAmount
      }
    },

    // 显示记录详情
    showRecordDetail(record) {
      this.selectedRecord = record
      this.showDetailPopup = true
    },

    // 关闭详情弹出层
    closeDetailPopup() {
      this.showDetailPopup = false
      this.selectedRecord = null
    },


    // 获取状态图标
    getStatusIcon(status) {
      switch (status) {
        case 0: return 'clock'
        case 1: return 'checkmark-circle'
        case 2: return 'close-circle'
        default: return 'clock'
      }
    },

    // 获取状态颜色
    getStatusColor(status) {
      switch (status) {
        case 0: return '#ff9500'
        case 1: return '#19be6b'
        case 2: return '#ed4014'
        default: return '#ff9500'
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 0: return '申请中'
        case 1: return '已打款'
        case 2: return '已拒绝'
        default: return '未知状态'
      }
    },

    // 格式化金额
    formatAmount(amount) {
      if (amount === null || amount === undefined || amount === '') return '0.00'
      const num = Number(amount)
      if (Number.isNaN(num)) return '0.00'
      return num.toFixed(2)
    },

    // 格式化银行卡号
    formatBankCard(cardNo) {
      if (!cardNo) return '-'
      if (cardNo.length <= 4) return cardNo
      return `**** **** **** ${cardNo.slice(-4)}`
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '-'
      try {
        // 如果是日期格式 "2025-09-23"，直接返回
        if (timeStr.includes('-') && timeStr.length === 10) {
          return timeStr
        }
        // 其他格式尝试解析
        const date = new Date(timeStr)
        if (isNaN(date.getTime())) {
          return timeStr
        }
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      } catch (error) {
        console.error('时间格式化错误:', error)
        return timeStr
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.withdrawal-record-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.scroll-content {
  height: 100vh;
}

/* 统计信息卡片 */
.stats-card {
  margin: 30rpx;
  background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
  border-radius: 20rpx;
  padding: 40rpx;
  display: flex;
  align-items: center;
  justify-content: space-around;
  box-shadow: 0 8rpx 30rpx rgba(74, 144, 226, 0.3);
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stats-value {
  font-size: 36rpx;
  font-weight: 700;
  color: #fff;
  margin-bottom: 8rpx;
}

.stats-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.stats-divider {
  width: 2rpx;
  height: 60rpx;
  background-color: rgba(255, 255, 255, 0.3);
}

/* 记录列表 */
.record-list {
  padding: 0 30rpx;
}

.record-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;

  &:active {
    background-color: #f8f9fa;
    transform: scale(0.995);
  }
}

.record-status {
  margin-right: 20rpx;
}

.status-icon {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  &.status-0 {
    background-color: rgba(255, 149, 0, 0.1);
  }

  &.status-1 {
    background-color: rgba(25, 190, 107, 0.1);
  }

  &.status-2 {
    background-color: rgba(237, 64, 20, 0.1);
  }
}

.record-content {
  flex: 1;
}

.record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.amount {
  font-size: 36rpx;
  font-weight: 700;
  color: #303133;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;

  &.status-0 {
    background-color: rgba(255, 149, 0, 0.1);
    .status-text {
      color: #ff9500;
    }
  }

  &.status-1 {
    background-color: rgba(25, 190, 107, 0.1);
    .status-text {
      color: #19be6b;
    }
  }

  &.status-2 {
    background-color: rgba(237, 64, 20, 0.1);
    .status-text {
      color: #ed4014;
    }
  }
}

.status-text {
  font-size: 22rpx;
  font-weight: 500;
}

.bank-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  gap: 20rpx;
}

.bank-name {
  font-size: 28rpx;
  color: #606266;
  font-weight: 500;
  flex: 1;
}

.bank-card {
  font-size: 26rpx;
  color: #909399;
  font-family: 'Monaco', 'Menlo', monospace;
}

.approval-time {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.time-label {
  font-size: 24rpx;
  color: #909399;
}

.time-value {
  font-size: 24rpx;
  color: #606266;
}

.record-arrow {
  margin-left: 20rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.6;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #6c757d;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #adb5bd;
  line-height: 1.5;
}

/* 加载状态 */
.load-status {
  padding: 40rpx 20rpx;
  display: flex;
  justify-content: center;
}

.load-more, .no-more {
  text-align: center;
}

.load-text, .no-more-text {
  font-size: 26rpx;
  color: #6c757d;
  padding: 16rpx 32rpx;
  background: #f8f9fa;
  border-radius: 50rpx;
  border: 1rpx solid #e9ecef;
}

/* 详情弹出层 */
.detail-popup {
  background-color: #fff;
  padding: 40rpx;
}

.detail-header {
  text-align: center;
  margin-bottom: 60rpx;
  padding-bottom: 30rpx;
  border-bottom: 2rpx solid #f5f7fa;
}

.detail-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #303133;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.detail-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f7fa;

  &:last-child {
    border-bottom: none;
  }
}

.detail-label {
  font-size: 28rpx;
  color: #909399;
  min-width: 140rpx;
}

.detail-value {
  font-size: 28rpx;
  color: #303133;
  text-align: right;
  flex: 1;

  &.amount-value {
    font-size: 32rpx;
    font-weight: 600;
    color: #4a90e2;
  }
}

.safe-area-bottom {
  height: calc(env(safe-area-inset-bottom) + 40rpx);
}
</style>
